package com.webber.demo;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 
 * <p>Title: UploadMixServlet.java</p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <p>ProjectName: uploadFile</p>
 * @Package com.webber.demo 
 * @author JobsZhang
 * @date 2017年10月19日 上午9:42:06
 * @version uploadFile 1.0
 */
public class UploadMixServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String serverPath = "E:/test/uploadFile";

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action =request.getParameter("action");
		//后台合并所有分块文件
		if("mergeChunks".equals(action)){
			mergeChunks(request, response);    
		} else if("checkChunk".equals(action)){//检查分片是否存在
			checkChunk(request, response);
		} else if("fileCheck".equals(action)){//检查文件是否存在
			fileCheck(request, response);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	/**
	 * 
	 * <p>Title: mergeChunks</p>
	 * <p>Description: 合并文件</p>
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author JobsZhang
	 * @date 2017年10月19日 上午9:42:31
	 */
	private void mergeChunks(HttpServletRequest request,HttpServletResponse response)  throws ServletException, IOException {
		System.out.println("开始合并文件...");
        //合并文件
        String fileMd5 = request.getParameter("fileMd5");
        String fileName = request.getParameter("fileName");

        //读取目录里面的所有文件
        File f = new File(serverPath+"/"+fileMd5);
        File[] fileArray = f.listFiles(new FileFilter(){
            //排除目录，只要文件
            public boolean accept(File pathname) {
                if(pathname.isDirectory()){
                    return false;
                }
                return true;
            }
        });

        //转成集合，便于排序
        List<File> fileList = new ArrayList<File>(Arrays.asList(fileArray));

        //从小到大排序
        Collections.sort(fileList, new Comparator<File>() {

            public int compare(File o1, File o2) {
                if(Integer.parseInt(o1.getName()) < Integer.parseInt(o2.getName())){
                    return -1;
                }
                return 1;
            }

        });

        File outputFile = new File(serverPath+"/"+fileName);

        //创建文件
         outputFile.createNewFile();

         //输出流
         FileChannel outChannel = new FileOutputStream(outputFile).getChannel();

         //合并
         FileChannel inChannel;
         for(File file : fileList){
             inChannel = new FileInputStream(file).getChannel();
             inChannel.transferTo(0, inChannel.size(), outChannel);
             inChannel.close();

             //删除分片
             file.delete();
         }
         //清除文件夹
         File tempFile = new File(serverPath+"/"+fileMd5);
         if(tempFile.isDirectory() && tempFile.exists()){
             tempFile.delete();
         }
         //关闭流
         outChannel.close();
         response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("{\"msg\":\"合并成功\"}");
	}
	/**
	 * 
	 * <p>Title: checkChunk</p>
	 * <p>Description: 检查该分块是否存在或者完整保存</p>
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws FileNotFoundException
	 * @author JobsZhang
	 * @date 2017年10月18日 下午11:24:32
	 */
    private void checkChunk(HttpServletRequest request,HttpServletResponse response) throws IOException,FileNotFoundException {
        System.out.println("checkChunk...");
        String fileMd5 = request.getParameter("fileMd5");
        String chunk = request.getParameter("chunk");
        String chunkSize = request.getParameter("chunkSize");

        File checkFile = new File(serverPath+"/"+fileMd5+"/"+chunk);

        response.setContentType("text/html;charset=utf-8");
        //检查文件是否存在，且大小是否一致
        if(checkFile.exists() && checkFile.length()==Integer.parseInt(chunkSize)){
            response.getWriter().write("{\"ifExist\":true,\"url\":\""+ serverPath+"/"+fileMd5+"/"+chunk +"\"}");
        }else{
            response.getWriter().write("{\"ifExist\":false,\"url\":\""+ serverPath+"/"+fileMd5+"/"+chunk +"\"}");
        }
    }
  /**
   * 
   * <p>Title: fileCheck</p>
   * <p>Description: 检查文件的md5数据是否跟在数据库存在</p>
   * @param request
   * @param response
   * @throws IOException
   * @throws FileNotFoundException
   * @author JobsZhang
   * @date 2017年10月19日 上午9:42:47
   */
    private void fileCheck(HttpServletRequest request, HttpServletResponse response) throws IOException, FileNotFoundException {
        String fileMd5 = request.getParameter("fileMd5");
        //模拟数据库
        Map<String,String> database = new HashMap<String,String>();
        database.put("576018603f4091782b68b78af85704a1", "测试");
        response.setContentType("text/html;charset=utf-8");
        if(database.containsKey(fileMd5)){
            response.getWriter().write("{\"ifExist\":1}");
        }else{
            response.getWriter().write("{\"ifExist\":0}");
        }
    }

}
